import { Hono } from 'hono'
import { logger } from 'hono/logger'
import { PDFDocument, rgb } from 'pdf-lib'
import fs from 'node:fs'
import path from 'node:path'

const app = new Hono()

app.use('*', logger())

app.post('/api/generate', async (c) => {
  const { rectangles } = await c.req.json();
  try {
    const pdfBuffer = fs.readFileSync(path.join(__dirname, 'public/example.pdf'));
    const pdfDoc = await PDFDocument.load(pdfBuffer);
    const page = pdfDoc.getPages()[0];
    const { height: pdfHeight } = page.getSize();

    const form = pdfDoc.getForm();

    rectangles.forEach((rect: any) => {
      // 确保坐标和尺寸已经按比例缩放
      const adjustedY = pdfHeight - rect.y - rect.height;

      const field = form.createTextField(rect.fieldName);
      field.addToPage(page, {
        x: rect.x,  // 使用缩放后的X坐标
        y: rect.y,  // 使用调整后的Y坐标
        width: rect.width,  // 使用缩放后的宽度
        height: rect.height,  // 使用缩放后的高度
        backgroundColor: rgb(0.95, 0.95, 0.95),
        borderColor: rgb(1, 1, 1),
        borderWidth: 1
      });
    });

    const modifiedPdfBytes = await pdfDoc.save();
    fs.writeFileSync(path.join(__dirname, 'public/modified.pdf'), modifiedPdfBytes);
    // 返回生成的PDF文件 弄成URL返回


    return c.json({ message: 'PDF modified successfully' });
  } catch (error) {
    console.error('Error processing PDF:', error);
    c.status(500);
    return c.json({ error: 'Internal Server Error' });
  }
})

console.log("Server running at http://localhost:3001")

export default {
  port: 3001,
  fetch: app.fetch,
}
